<template>
  <div class="search">

    <div class="search-content" v-if="hasSearched">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="歌曲" name="songs">
          <div v-if="songs.length > 0">
            <el-table
              :data="songs"
              stripe
              style="width: 100%"
              @row-click="playSong"
            >
              <el-table-column type="index" label="序号" width="60" />

              <el-table-column prop="name" label="歌曲名" min-width="200">
                <template #default="scope">
                  <span class="song-name">{{ scope.row.name }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="singer" label="歌手" min-width="150" />

              <el-table-column prop="album" label="专辑" min-width="200" />

              <el-table-column prop="duration" label="时长" width="100">
                <template #default="scope">
                  {{ formatDuration(scope.row.duration) }}
                </template>
              </el-table-column>

              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button type="primary" icon="Play" circle @click.stop="playSong(scope.row)" />
                  <el-button icon="Plus" circle @click.stop="addToPlaylist(scope.row)" />
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination" v-if="songs.length > 0">
              <el-pagination
                v-model:current-page="songsPage"
                v-model:page-size="songsPageSize"
                :total="songsTotal"
                layout="prev, pager, next, jumper, ->, total"
                @current-change="(page) => handlePageChange(page, 'songs')"
              />
            </div>
          </div>
          <div v-else class="no-results">
            <p>未找到相关歌曲</p>
          </div>
        </el-tab-pane>

        <el-tab-pane label="歌手" name="singers">
          <div v-if="singers.length > 0">
            <div class="singer-grid">
              <el-card
                v-for="singer in singers"
                :key="singer.id"
                class="singer-card"
                @click="goToSingerDetail(singer.id)"
              >
                <div class="singer-avatar">
                  <img
                    :src="singer.picUrl || singerDefaultImage"
                    :alt="singer.name"
                    @error="handleImageError"
                  />
                </div>
                <div class="singer-info">
                  <h3>{{ singer.name }}</h3>
                  <p class="singer-brief">{{ singer.briefDesc || '暂无简介' }}</p>
                </div>
              </el-card>
            </div>

            <div class="pagination" v-if="singers.length > 0">
              <el-pagination
                v-model:current-page="singersPage"
                v-model:page-size="singersPageSize"
                :total="singersTotal"
                layout="prev, pager, next, jumper, ->, total"
                @current-change="(page) => handlePageChange(page, 'singers')"
              />
            </div>
          </div>
          <div v-else class="no-results">
            <p>未找到相关歌手</p>
          </div>
        </el-tab-pane>

        <el-tab-pane label="专辑" name="albums">
          <div v-if="albums.length > 0">
            <div class="album-grid">
              <el-card
                v-for="album in albums"
                :key="album.id"
                class="album-card"
                @click="goToAlbumDetail(album.id)"
              >
                <div class="album-cover">
                  <img
                    :src="album.picUrl || albumDefaultImage"
                    :alt="album.name"
                    @error="handleImageError"
                  />
                </div>
                <div class="album-info">
                  <h3 class="album-name">{{ album.name }}</h3>
                  <p class="album-singer">{{ album.singer }}</p>
                  <p class="album-publish-time">{{ formatDate(album.publishTime) }}</p>
                </div>
              </el-card>
            </div>

            <div class="pagination" v-if="albums.length > 0">
              <el-pagination
                v-model:current-page="albumsPage"
                v-model:page-size="albumsPageSize"
                :total="albumsTotal"
                layout="prev, pager, next, jumper, ->, total"
                @current-change="(page) => handlePageChange(page, 'albums')"
              />
            </div>
          </div>
          <div v-else class="no-results">
            <p>未找到相关专辑</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="hot-search" v-else>
      <h3>热门搜索</h3>
      <div class="hot-keywords">
        <el-tag
          v-for="keyword in hotKeywords"
          :key="keyword"
          class="hot-keyword"
          @click="searchByKeyword(keyword)"
        >
          {{ keyword }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted,watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePlayerStore } from '@/store/player'
import { ElMessage } from 'element-plus'
import defaultSingerImage from '@/assets/img/singer-default.png'
import defaultAlbumImage from '@/assets/img/song-default.png'
import { searchSongs, searchSingers, searchAlbums } from '@/services/search'

export default {
  name: 'Search',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const playerStore = usePlayerStore()

    // 默认图片
    const singerDefaultImage = defaultSingerImage
    const albumDefaultImage = defaultAlbumImage

    // 搜索相关
    const searchKeyword = ref('')
    const hasSearched = ref(false)
    const activeTab = ref('songs')

    // 搜索结果
    const songs = ref([])
    const singers = ref([])
    const albums = ref([])
    const songLists = ref([])

    // 分页相关
    const songsPage = ref(1)
    const songsPageSize = ref(20)
    const songsTotal = ref(0)

    const singersPage = ref(1)
    const singersPageSize = ref(20)
    const singersTotal = ref(0)

    const albumsPage = ref(1)
    const albumsPageSize = ref(20)
    const albumsTotal = ref(0)

    const songListsPage = ref(1)
    const songListsPageSize = ref(20)
    const songListsTotal = ref(0)

    // 热门搜索关键词
    const hotKeywords = ref([
      '周杰伦', '林俊杰', '陈奕迅', 'Taylor Swift', '热门歌曲', '新歌', '流行', '摇滚'
    ])

    // 执行搜索
    const performSearch = async (keyword, type = 'songs', page = 1) => {
      try {
        switch (type) {
          case 'songs':
            const songResponse = await searchSongs(keyword, page, songsPageSize.value)
            if (songResponse.code === '1') {
              songs.value = (songResponse.data.list || songResponse.data).map(song => ({
                id: song.songId || song.id,
                name: song.songName || song.name,
                singer: song.singerName || song.singer,
                album: song.songAlbum || song.album,
                duration: song.duration,
                url: `/api/song/songById/${song.songId || song.id}`
              }))
              songsTotal.value = songResponse.data.total || songs.value.length
            } else {
              songs.value = []
              songsTotal.value = 0
              ElMessage.error('搜索歌曲失败')
            }
            break

          case 'singers':
            const singerResponse = await searchSingers(keyword, page, singersPageSize.value)
            if (singerResponse.code === '1') {
              singers.value = (singerResponse.data.list || singerResponse.data).map(singer => ({
                id: singer.singerId || singer.id,
                name: singer.singerName || singer.name,
                briefDesc: singer.singerIntro || singer.briefDesc,
                picUrl: singer.singerPic || singer.picUrl
              }))
              singersTotal.value = singerResponse.data.total || singers.value.length
            } else {
              singers.value = []
              singersTotal.value = 0
              ElMessage.error('搜索歌手失败')
            }
            break

          case 'albums':
            const albumResponse = await searchAlbums(keyword, page, albumsPageSize.value)
            if (albumResponse.code === '1') {
              albums.value = (albumResponse.data.list || albumResponse.data).map(album => ({
                id: album.albumId || album.id,
                name: album.albumName || album.name,
                singer: album.singerName || album.singer,
                publishTime: album.publishTime,
                picUrl: album.albumPic || album.picUrl
              }))
              albumsTotal.value = albumResponse.data.total || albums.value.length
            } else {
              albums.value = []
              albumsTotal.value = 0
              ElMessage.error('搜索专辑失败')
            }
            break
        }
      } catch (error) {
        ElMessage.error('搜索失败: ' + error.message)
      }
    }

    // 执行搜索
    const handleSearch = async () => {
      if (!searchKeyword.value.trim()) {
        ElMessage.warning('请输入搜索关键词')
        return
      }

      hasSearched.value = true
      await performSearch(searchKeyword.value, activeTab.value, 1)
    }

    // 通过热门关键词搜索
    const searchByKeyword = (keyword) => {
      searchKeyword.value = keyword
      hasSearched.value = true
      performSearch(keyword, activeTab.value, 1)
    }

    // 处理分页变化
    const handlePageChange = (page, type) => {
      switch (type) {
        case 'songs':
          songsPage.value = page
          performSearch(searchKeyword.value, 'songs', page)
          break
        case 'singers':
          singersPage.value = page
          performSearch(searchKeyword.value, 'singers', page)
          break
        case 'albums':
          albumsPage.value = page
          performSearch(searchKeyword.value, 'albums', page)
          break
        case 'songlists':
          songListsPage.value = page
          performSearch(searchKeyword.value, 'songlists', page)
          break
      }
    }

    // 播放歌曲
    const playSong = (song) => {
      playerStore.setCurrentSong(song)
      ElMessage.success(`正在播放: ${song.name}`)
    }

    // 添加到播放列表
    const addToPlaylist = (song) => {
      playerStore.addToPlaylist(song)
      ElMessage.success(`已添加到播放列表: ${song.name}`)
    }

    // 跳转到歌手详情
    const goToSingerDetail = (singerId) => {
      router.push(`/singer/${singerId}`)
    }

    // 跳转到专辑详情
    const goToAlbumDetail = (albumId) => {
      router.push(`/album/${albumId}`)
    }

    // 格式化时长
    const formatDuration = (seconds) => {
      if (!seconds) return '0:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
    }

    // 格式化播放量
    const formatCount = (count) => {
      if (count >= 10000) {
        return (count / 10000).toFixed(1) + '万'
      }
      return count
    }

    // 处理图片加载错误
    const handleImageError = (e) => {
      const src = e.target.src
      if (src.includes('singer')) {
        e.target.src = singerDefaultImage
      } else if (src.includes('album')) {
        e.target.src = albumDefaultImage
      } else {
        // 默认处理
        e.target.src = singerDefaultImage
      }
    }

    // 初始化加载
    onMounted(() => {
      // 如果URL中有搜索关键词，则执行搜索
      if (route.query.keyword) {
        searchKeyword.value = route.query.keyword
        hasSearched.value = true
        performSearch(route.query.keyword, activeTab.value, 1)
      }
    })

    watch(activeTab, (newTab) => {
      if (hasSearched.value) {
        // 根据当前标签页执行对应类型的搜索
        switch (newTab) {
          case 'songs':
            if (songs.value.length === 0 && songsTotal.value === 0) {
              performSearch(searchKeyword.value, 'songs', songsPage.value)
            }
            break
          case 'singers':
            if (singers.value.length === 0 && singersTotal.value === 0) {
              performSearch(searchKeyword.value, 'singers', singersPage.value)
            }
            break
          case 'albums':
            if (albums.value.length === 0 && albumsTotal.value === 0) {
              performSearch(searchKeyword.value, 'albums', albumsPage.value)
            }
            break
        }
      }
    })

    return {
      searchKeyword,
      hasSearched,
      activeTab,
      songs,
      singers,
      albums,
      songLists,
      songsPage,
      songsPageSize,
      songsTotal,
      singersPage,
      singersPageSize,
      singersTotal,
      albumsPage,
      albumsPageSize,
      albumsTotal,
      songListsPage,
      songListsPageSize,
      songListsTotal,
      hotKeywords,
      singerDefaultImage,
      albumDefaultImage,
      handleSearch,
      searchByKeyword,
      handlePageChange,
      playSong,
      addToPlaylist,
      goToSingerDetail,
      goToAlbumDetail,
      formatDuration,
      formatDate,
      formatCount,
      handleImageError
    }
  }
}
</script>

<style scoped>
.search {
  padding: 20px;
}

.search-header {
  margin-bottom: 30px;
}

.search-box {
  max-width: 600px;
  margin: 0 auto;
}

.search-content {
  margin-top: 20px;
}

.hot-search h3 {
  text-align: center;
  margin-bottom: 20px;
}

.hot-keywords {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 15px;
}

.hot-keyword {
  cursor: pointer;
  font-size: 16px;
  padding: 10px 15px;
}

.hot-keyword:hover {
  transform: scale(1.05);
  transition: transform 0.2s ease;
}

.singer-grid,
.album-grid,
.song-list-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.singer-card,
.album-card,
.song-list-card {
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.singer-card:hover,
.album-card:hover,
.song-list-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.singer-avatar,
.album-cover,
.song-list-cover {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
}

.singer-avatar img,
.album-cover img,
.song-list-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-count {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 2px 5px;
  border-radius: 10px;
  font-size: 12px;
}

.singer-info,
.album-info,
.song-list-info {
  padding: 15px 10px 10px;
}

.singer-info h3,
.album-name,
.song-list-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.singer-brief,
.album-singer,
.song-list-user,
.album-publish-time {
  margin: 0;
  color: #999;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.singer-brief {
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.song-name {
  font-weight: 500;
  cursor: pointer;
}

.song-name:hover {
  color: #409eff;
}

.no-results {
  text-align: center;
  padding: 50px 0;
  color: #999;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
